import './discountAdd.scss';
import { useState, useEffect } from 'react';
import * as moment from 'moment';
import { setTime } from '../../../../../utils/setTime'
import {
    Breadcrumb,
    DatePicker,
    Form,
    Input,
    Radio,
    Checkbox,
    Button,
    Space,
    Table,
    Select,
    Divider,
    Modal,
    message,
    Popconfirm
} from 'antd';
import { useNavigate } from 'react-router-dom';
import request from '../../../../../utils/request';
const DiscountAdd = () => {
    useEffect(() => {
        addgetDatas()
        request.addDiscountData().then(res => {
            if (res.code == 200) { setPopoutDatas(res.data) }
        })
    }, [])
    const addgetDatas = () => {
        request.addgetData().then(res => {
            console.log(res);
            if (res.code == 200) { setDate(res.data) }
        })
    }
    const Navigate = useNavigate()
    //创建form实例
    const [addForm] = Form.useForm()
    //表格条数
    const showTotal = (total) => `数量 ${total} 条`;
    //下部分数据
    const [data, setDate] = useState([])
    //下部分表头
    const columns = [
        {
            dataIndex: 'goodsId',
            key: 'goodsId',
            align: 'center',
        },
        {
            title: '商品信息',
            dataIndex: 'goodsName ',
            key: 'goodsName ',
            align: 'center',
            render: (_, record) => (
                <div className='divImg'>
                    <div></div>
                    <div>
                        <Button type="link">{record.goodsName}</Button>
                        <div>库存{record.inventory}</div>
                    </div>
                </div>
            ),
        },
        {
            title: '原价 (元)',
            dataIndex: 'price',
            key: 'price',
            align: 'center',
        },
        {
            title: '折扣',
            dataIndex: 'discount',
            key: 'discount',
            align: 'center',
            render: (_, record) => (
                <Input placeholder='请输入' style={{ marginLeft: '1%' }} value={record.discount}></Input>
            ),
        },
        {
            title: '折扣 (元)',
            key: 'discountPrice',
            dataIndex: 'discountPrice',
            align: 'center',
            render: (_, record) => (
                <Input placeholder='请输入' style={{ marginLeft: '1%' }} value={record.discountPrice}>
                </Input>
            ),
        },
        {
            title: '操作',
            key: 'operation',
            dataIndex: 'operation',
            align: 'center',

            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => { editList(record) }}>修改</Button>
                    <Popconfirm
                        title="是否确定删除此条内容?"
                        onCancel={cancel}
                        onConfirm={() => { confirm(record) }}
                        cancelText="取消"
                        okText="确定"
                    >
                        <Button type="link">删除</Button>
                    </Popconfirm>

                </Space>
            ),
        },
    ];
    //上部分表单提交验证

    const onFinish = (values) => {
        let addData = addForm.getFieldsValue()
        // addData.startTime = addData.startTime != null ? setTime(addData.startTime._d) : alert('请选择开始时间')
        // addData.endTime = addData.endTime != null ? setTime(addData.endTime._d) : alert('请选择结束时间')
        let time1 = moment.utc(addData.startTime)
        let time2 = moment.utc(addData.endTime)
        addData.startTime = time1.format()
        addData.endTime = time2.format()
        addData.isshowUnderlinedPrice = addData.isshowUnderlinedPrice == true ? 1 : 0
        addData.promotionWipezero = addData.promotionWipezero == true ? 1 : 0
        if (addData.commodityPurchaseLimit == undefined) {
            addData.commodityPurchaseLimit = 0
        }
        //新建
        request.addDiscount(addData).then(res => {
            if (res.code == 200) {
                message.success('添加成功')
            }
        })
    };
    const onFinishFailed = (values) => {

    };
    const [isInput, setIsInput] = useState(false)
    //弹框数据
    const [PopoutDatas, setPopoutDatas] = useState([])
    //弹框表头
    const adDcolumns = [
        {
            title: '商品信息',
            dataIndex: 'goodsName',
            key: 'goodsName',
            align: 'center',

        },
        {
            title: '价格 (元)',
            dataIndex: 'price',
            key: 'price',
            align: 'center',
        },
        {
            title: '库存',
            dataIndex: 'inventory',
            key: 'inventory',
            align: 'center',
        },
        {
            title: '销量',
            key: 'sales',
            dataIndex: 'sales',
            align: 'center',
        },
        {
            key: 'goodsId',
            dataIndex: 'goodsId',
            align: 'center',
        }
    ];
    //弹框表格方法
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(selectedRowKeys, selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            name: record.name,
        }),
    };
    //多选框
    const [selectionType, setSelectionType] = useState('checkbox');
    //创建添加弹框表单实例
    const [PopoutForm] = Form.useForm()
    //弹框条数
    const showTotals = (total) => `数量 ${total} 条`;
    //弹框显示隐藏
    const [isModalVisible, setIsModalVisible] = useState(false);
    //弹框显示隐藏
    const showModal = () => {
        setIsModalVisible(true);
    };
    //单框点击确定
    const handleOk = (v) => {
        console.log(v);
        setIsModalVisible(false);
    };
    //弹框表单
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    //input验证
    const PopoutFinish = (v) => {
        let PopoutData = PopoutForm.getFieldsValue()
    }
    //弹框重置
    const PopoutFailed = () => {

    }
    //选择类别
    const changeClass = (v) => {
        console.log(v);
    }
    //确认删除
    const confirm = (record) => {
        //拿到列
        request.delDiscount(record.discountId).then(res => {
            if (res.code == 200) {
                message.success('已删除');
            }
        })

    };
    //取消
    const cancel = (e) => {
        message.error('已取消');
    };
    //修改框
    const [editisModalVisible, setEditisModalVisible] = useState(false);
    const [editForm] = Form.useForm()
    const [discountId, setDiscountId] = useState('')
    const editList = (record) => {
        setEditisModalVisible(true);
        editForm.setFieldsValue(record)
        setDiscountId(record.discountId)
    };
    const editCancel = () => {
        setEditisModalVisible(false);
    };
    const setEdit = () => {
        setEditisModalVisible(false);
        let editData = editForm.getFieldsValue()
        editData.discountId = discountId
        request.editDiscount(editData).then(res => {
            console.log(res);
            if (res.code == 200) {
                addgetDatas()
                message.success('修改成功')
            }
        })
    }
    //商品弹框查询
    const inquire = () => {
        let PopoutData = PopoutForm.getFieldsValue()
        if (PopoutData.goodsName || PopoutData.Popouts) {
            if (PopoutData.goodsName && PopoutData.Popouts) {
                request.setDiscountData(PopoutData).then(res => {
                    console.log(res);
                })
            } else if (PopoutData.goodsName) {
                request.setDiscountData(PopoutData.goodsName).then(res => {
                    console.log(res);
                })
            } else {
                request.setDiscountData(PopoutData.Popouts).then(res => {
                    console.log(res);
                })
            }

        }


    }
    return (
        <div className='AddBox'>
            <div className='divPre'>
                <Breadcrumb>
                    <Breadcrumb.Item>营销</Breadcrumb.Item>
                    <Breadcrumb.Item>限时折扣</Breadcrumb.Item>
                    <Breadcrumb.Item>新建折扣活动</Breadcrumb.Item>
                </Breadcrumb>
                <h2>新建折扣互动</h2>
            </div>
            <div>

                <Form labelCol={{ span: 4, }}
                    wrapperCol={{ span: 14, }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    layout="horizontal"
                    form={addForm}
                >
                    <div className='divContent'>
                        <div style={{ paddingTop: '20px' }}>基础信息</div>
                        <Form.Item label="活动名称" name='eventName'>
                            <Input placeholder='请输入' style={{ width: '400px' }} />
                        </Form.Item>

                        <Form.Item label="活动日期" style={{ marginBottom: 0 }} >
                            <Form.Item style={{ display: 'inline-block', width: 'calc(30% - 12px)' }} name='startTime'>
                                <DatePicker showTime={true} />
                            </Form.Item>
                            <span style={{ display: 'inline-block', width: '24px', lineHeight: '32px', textAlign: 'center' }}>
                                至
                            </span>
                            <Form.Item style={{ display: 'inline-block', width: 'calc(60% - 12px)' }} name='endTime'>
                                <DatePicker showTime={true} />
                            </Form.Item>
                        </Form.Item>


                        <Form.Item label="优惠券叠加" name='couponIsstacking'>
                            <Radio.Group>
                                <Radio value={0} style={{ display: 'block' }}>不可叠加</Radio>
                                <Radio value={1} style={{ paddingTop: '10px' }}> 可叠加其他类型的优惠 </Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="促销抹零" valuePropName='checked' name='promotionWipezero'>
                            <Checkbox>抹零</Checkbox>
                        </Form.Item>
                        <Form.Item label="商品限购" valuePropName='checked'>
                            <Checkbox onChange={() => { setIsInput(!isInput) }} >不限购</Checkbox>
                        </Form.Item>
                        <Form.Item label='最多购买' name='commodityPurchaseLimit'>
                            <Input addonAfter="件" placeholder='请输入' disabled={isInput} style={{ width: '140px' }} />
                        </Form.Item>
                        <Form.Item label="划线价" style={{ marginTop: '-10px' }} valuePropName='checked' name='isshowUnderlinedPrice'>
                            <Checkbox>显示划线价</Checkbox>
                        </Form.Item>
                        <Form.Item label="状态" name="activeStatus">
                            <Select style={{ width: '140px' }} placeholder='请选择活动状态'>
                                <Select.Option >全部</Select.Option>
                                <Select.Option value='未开始'>未开始</Select.Option>
                                <Select.Option value='进行中'>进行中</Select.Option>
                                <Select.Option value='已结束'>已结束</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item style={{ paddingBottom: '30px' }}>
                            <Button type='primary' htmlType="submit" style={{ marginRight: '10px' }}>提交</Button>
                            <Button onClick={() => { Navigate('/home/market/time-discount') }}>返回</Button>
                        </Form.Item>
                    </div>
                    <div>
                        <Modal title="修改商品" visible={editisModalVisible} onCancel={editCancel} closable={false} footer="">
                            <Form
                                // initialValues={editisModalVisible}
                                form={editForm}
                            >
                                <Form.Item style={{ width: '370px', margin: '10px auto' }} label='折扣' name='discount'>
                                    <Input defaultValue={editisModalVisible.discount} ></Input>
                                </Form.Item>
                                <Form.Item style={{ width: '370px', margin: '10px auto' }} label='折扣 (元)' name='discountPrice'>
                                    <Input defaultValue={editisModalVisible.discountPrice}></Input>
                                </Form.Item>
                                <Divider />
                                <Form.Item style={{ display: 'flex', justifyContent: 'center' }}>
                                    <Button type='primary' style={{ marginLeft: '45px', marginRight: '40px' }} onClick={setEdit}>确定</Button>
                                    <Button onClick={() => { setEditisModalVisible(false); }}>取消</Button>
                                </Form.Item>
                            </Form>
                        </Modal>
                    </div>
                </Form>




                <Form>
                    <div className='divNext' >
                        <div className='NextTit'>
                            <span>折扣商品列表</span>
                            <Button type="primary" onClick={showModal}>+ 添加商品</Button>
                        </div>
                        <Table columns={columns} dataSource={data} pagination={{
                            total: data.length,
                            showTotal: showTotal,
                            showSizeChanger: true,
                            showQuickJumper: true,
                        }}
                            rowKey={(record) => record.discountId}
                        />
                        <Form.Item className='NextFeature'>
                            <Button type="primary" htmlType="submit">提交 </Button>
                            <Button onClick={() => { Navigate('/home/market/time-discount') }}>返回</Button>
                        </Form.Item>
                    </div>
                    <Modal visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} width='1000px' footer="" >
                        <div className='PopoutBox'>
                            <Form
                                onFinish={PopoutFinish}
                                onFinishFailed={PopoutFailed}
                                autoComplete="off"
                                layout="horizontal"
                                form={PopoutForm}
                            >
                                <div className='PopoutTit'>选择商品</div>
                                <Divider />
                                <div className='PopoutContent'>
                                    <div className='PopoutIn' >
                                        <div style={{ marginRight: '20px' }}>全部分类</div>
                                        <Form.Item style={{ margin: '0 auto', marginRight: '20px' }} name='discount'>
                                            <Select style={{ width: '200px' }} placeholder='请选择商品分类' onChange={changeClass}>
                                                <Select.Option value={111}>分类1</Select.Option>
                                                <Select.Option value={666}>分类2</Select.Option>
                                                <Select.Option value={888}>分类3</Select.Option>
                                            </Select>
                                        </Form.Item>
                                        <Form.Item style={{ margin: '0 auto' }} name='goodsName'>
                                            <Input style={{ width: '200px' }} placeholder='请输入' ></Input>
                                        </Form.Item>
                                    </div>
                                    <div>
                                        <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }} onClick={inquire}> 查询</Button>
                                        <Button>重置</Button>
                                    </div>
                                </div>
                                <Table rowSelection={{ type: selectionType, ...rowSelection, }}
                                    rowKey={(record) => record.goodsId}
                                    columns={adDcolumns} dataSource={PopoutDatas}
                                    style={{ width: '96%', margin: '0 auto' }}
                                    pagination={{
                                        total: PopoutDatas.length, showTotals: showTotals,
                                        showSizeChanger: true, showQuickJumper: true,
                                    }}
                                >
                                </Table>
                                <div className='location'>
                                    <Button style={{ marginRight: '20px' }} onClick={handleCancel}> 取消</Button>
                                    <Button type="primary" htmlType="submit" onClick={handleOk}>确认</Button>
                                </div>
                            </Form>
                        </div>
                    </Modal>
                </Form>
            </div>
        </div >
    )
}
export default DiscountAdd;